package test.netty.core.chapter1.socket;

import lombok.extern.slf4j.Slf4j;
import test.netty.common.exceptions.NettyException;

import java.io.FileOutputStream;
import java.io.RandomAccessFile;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;

/**
 * <p>标题: SocketChannelClientDemo</p>
 * <p>功能描述: </p>
 *
 * <p>创建时间: 2021-04-03,20:18</p>
 * <p>作者：chaiys</p>
 **/
@Slf4j
public class SocketChannelClientDemo {

    public static void main(String[] args) {
        String readFilePath = "E:\\File\\电脑信息\\详细报表aaa.txt";
        try {
            // 1. 通到打开(客户端和服务端通道)
            SocketChannel client = SocketChannel.open();
            // 2. 连接服务器
            client.connect(new InetSocketAddress("127.0.0.1", 9001));
            log.info("=====连接服务器成功=====");
            // 3. 通过通道发数据
            // 这里的"rw"是指支持读和写
            RandomAccessFile randomAccessFile = new RandomAccessFile(readFilePath,"rw");
            // 4. 创建硬盘到内存的通道
            FileChannel readChannel = randomAccessFile.getChannel();
            // 5. 循环读取到内存中
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            int size = -1;
            while ((size = readChannel.read(byteBuffer)) != -1) {
                byteBuffer.clear();
                client.write(byteBuffer); //循环写入（客户端和服务端的通道）
                byteBuffer.flip();
            }
            client.close();
        } catch (Exception e) {
            log.error("文件传输到服务器失败！", e);
            throw new NettyException("文件传输到服务器失败！", e);
        }
    }
}
